package com.cli.springboottemplateengine.engine;

import groovy.lang.Writable;
import groovy.text.StreamingTemplateEngine;
import org.springframework.stereotype.Component;

import java.io.StringWriter;
import java.util.Map;

@Component
public class GroovyStreamingTemplateEngine implements TemplateEngine {
    private final StreamingTemplateEngine engine;

    public GroovyStreamingTemplateEngine() {
        engine = new StreamingTemplateEngine();
    }

    @Override
    public String doRender(String templateContent, Map<String, Object> model) {
        try {
            Writable output = engine.createTemplate(templateContent).make(model);
            StringWriter writer = new StringWriter();
            output.writeTo(writer);
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException("Groovy 渲染失败", e);
        }
    }

    @Override
    public String getType() {
        return "groovy";
    }
}
